//
//  RegisterViewController.m
//  MyNewProject
//
//  Created by sun on 2019/2/13.
//  Copyright © 2019 sun. All rights reserved.
//

#import "RegisterViewController.h"
#import "CQCountDownButton.h"
#import "SVProgressHUD.h"
#import "YPLoginDataModels.h"
#import "UIButton+LXMImagePosition.h"
#import "XMJSWebViewController.h"
#import "SignViewController.h"
#import "CertifyViewController.h"

#pragma mark -- mark model
#import "WXLoginModel.h"

@interface RegisterViewController ()<UIScrollViewDelegate, UITextFieldDelegate>
@property (nonatomic, strong) UIScrollView *myScroll;

@property (nonatomic, strong) CQCountDownButton *countDownButton;

@property (nonatomic, strong) UITextField * currentTextField;
@property (nonatomic, assign)BOOL isSelect;
@property (nonatomic, strong)UIButton * xiYiBtn;
@property (nonatomic, strong) UIButton *userXieYiBtn;

@property (nonatomic, strong)UIImage * myImage;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navBackgroundColor = [UIColor whiteColor];
    
    [self initNav];

    SKAdd_Observer(@"XIYIQIANMING",self, updateXieYiBtn:, nil);
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keboardDismiss:)];
    [self.myScroll addGestureRecognizer:tapGesture];
    [self initView];
    
}

-(void)keboardDismiss:(UIGestureRecognizer*)gesture
{
    [self.view endEditing:YES];

}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    self.currentTextField = textField;
    return true;
}
-(void)initView
{
    
//    NSArray * placeholderArr = @[@"请输入你的手机号",@"请填写验证码",@"请填写您的登陆密码",@"请再次确认您的登陆密码",@"请填写邀请码（必填）"];
    NSArray * placeholderArr = @[@"请输入你的手机号",@"请填写验证码",@"请填写密码",@"请填写邀请码（选填）"];
    for (int i = 0; i<4; i++) {
        UITextField * accountTextField =[[UITextField alloc] initWithFrame:CGRectMake(43, 47 + (40 +36) * i, SCREEN_WIDTH-43*2, 40)];
        accountTextField.tag =  20000000 +i;
        accountTextField.font = [UIFont systemFontOfSize:16.0f];
        accountTextField.placeholder = placeholderArr[i];
        accountTextField.delegate = self;
        [self.myScroll addSubview:accountTextField];
        UIView *lineView = [[UIView alloc] init];
        lineView.tag = 20000000 +i;
        lineView.frame = CGRectMake(42.5,accountTextField.bottom,SCREEN_WIDTH - 42.5 *2,0.5);
        lineView.backgroundColor = [UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0];
        [self.myScroll addSubview:lineView];
        if (i == 1) {
            accountTextField.frame = CGRectMake(43, 47 + (40 +36) * i, SCREEN_WIDTH-43*2-97, 40);
            [self countCutDown:accountTextField];
        }
        
    }
    UIView * lineView = [self.myScroll viewWithTag:20000000+3];
//    NSString * string = @"我已认真阅读并同意《用户协议》";
    NSString * colorStr1 = @"我已认真阅读并同意";
    CGFloat width1 = [NSString getWidthWithString:colorStr1 font:SKFONT_SIZE(14) lineBreakModel:NSLineBreakByCharWrapping];
    UIButton * butn = [UIButton buttonWithType:UIButtonTypeCustom];
    butn.frame = CGRectMake(lineView.left, lineView.bottom +5, width1 +15, 30);
//    butn.titleLabel.font = SKFONT_SIZE(14);
//    [butn setTitle:colorStr1 forState:UIControlStateNormal];
//    [butn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:colorStr1];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:[colorStr1 rangeOfString:@"我已认真阅读并同意"]];

    [attString addAttribute:(NSString*)NSFontAttributeName value:SKFONT_SIZE(14) range:[colorStr1 rangeOfString:@"我已认真阅读并同意"]];

    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:SKColorWithHex(0x7ab801) range:[colorStr1 rangeOfString:@"《用户协议》"]];
    [attString addAttribute:(NSString*)NSFontAttributeName value:SKFONT_SIZE(14) range:[colorStr1 rangeOfString:@"《用户协议》"]];
    [butn setAttributedTitle:attString forState:UIControlStateNormal];

    butn.titleLabel.textAlignment = NSTextAlignmentLeft;
    butn.titleLabel.lineBreakMode = NSLineBreakByCharWrapping;

    [butn addTarget:self action:@selector(userSelectEvent:) forControlEvents:UIControlEventTouchUpInside];
    [butn setImage:SKIMAGE_NAMED(@"unSelectImage") forState:UIControlStateNormal];
    [butn setImage:SKIMAGE_NAMED(@"selectImage") forState:UIControlStateSelected];
    butn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [butn setImagePosition:LXMImagePositionLeft spacing:5];
    [self.myScroll addSubview:butn];
    self.xiYiBtn = butn;
    NSString * colorStr = @"《用户协议》";
    CGFloat width = [NSString getWidthWithString:colorStr font:SKFONT_SIZE(14) lineBreakModel:NSLineBreakByCharWrapping];


    UIButton * butn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    butn1.frame = CGRectMake(butn.right, lineView.bottom +5, width, 30);
    butn1.titleLabel.font = SKFONT_SIZE(14);
    [butn1 setTitle:colorStr forState:UIControlStateNormal];
    [butn1 setTitleColor:SKColorWithHex(0x7ab801) forState:UIControlStateNormal];
    [butn1 addTarget:self action:@selector(userEvent:) forControlEvents:UIControlEventTouchUpInside];
    butn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.myScroll addSubview:butn1];
    self.userXieYiBtn = butn1;
    
    UIFont * font = SKFONT_Semibold(18);
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(43, lineView.bottom +49 , SCREEN_WIDTH -43 *2 , 44);
    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    button.backgroundColor = SKColorWithHex(0xE33030);
    [button setTitle:@"注 册" forState:UIControlStateNormal];
    button.titleLabel.font = font ;
    [button setTitleColor:SKColorWithHex(0xFFFFFF) forState:UIControlStateNormal];
    [button addTarget:self action:@selector(registerDeal:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = 520;
    [self.myScroll addSubview:button];
    if (button.bottom +100 >SCREENH_HEIGHT-SKTopBar_Height) {
        _myScroll.contentSize = CGSizeMake(SCREEN_WIDTH, button.bottom +100);
    }
}
-(void)updateXieYiBtn:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
    self.myImage = infoDic[@"MYSignImage"];
    NSLog(@"--------%@---------",self.myImage);
}

-(void)userSelectEvent:(UIButton*)sender
{
    sender.selected = !sender.selected;
}

-(void)userEvent:(UIButton*)sender
{
    [SVProgressHUD show];
    [YQNetworking postWithUrl:@"Index/getNotice" refreshRequest:YES cache:NO params:@{@"type":@(8)} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [SVProgressHUD dismiss];
        XMJSWebViewController * webVC = [[XMJSWebViewController alloc]init];
        webVC.type = WebType_H5_content;
        webVC.titleString = @"注册协议";
        webVC.isJianMing = false;
        webVC.fileUrl = SafeString(response[@"data"][0][@"contents"]);
        [self.navigationController pushViewController:webVC animated:YES];
        
    } failBlock:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}
#pragma mark --- 倒计时button
-(void)countCutDown:(UITextField *)accountTextField
{
    
    SKWeakSelf;
    self.countDownButton = [[CQCountDownButton alloc] initWithDuration:10 buttonClicked:^{
        NSLog(@"按钮点击");
        UITextField * mobileTextField =[weakSelf.myScroll viewWithTag:20000000];
        [SVProgressHUD showWithStatus:@"正在获取验证码..."];
        [YQNetworking postWithUrl:@"Login/sendsms" refreshRequest:YES cache:NO params:@{@"mobile":mobileTextField.text,@"sign":@"yupinyouxuan*****yupinyouxuan"} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {

        } successBlock:^(id response) {

            NSDictionary *dic = (NSDictionary*)response;
            if ([dic[@"status"] isEqualToString:@"ok"])
            {
                [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
                [weakSelf.countDownButton startCountDown];
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:@"获取失败，请重试"];
                weakSelf.countDownButton.enabled = YES;

            }
        } failBlock:^(NSError *error) {

        }];
        
    } countDownStart:^{
        //------- 倒计时开始 -------//
        NSLog(@"倒计时开始");
    } countDownUnderway:^(NSInteger restCountDownNum) {
        //------- 倒计时进行中 -------//
        [weakSelf.countDownButton setTitle:[NSString stringWithFormat:@"重新获取(%ld)", restCountDownNum] forState:UIControlStateNormal];
    } countDownCompletion:^{
        //------- 倒计时结束 -------//
        [weakSelf.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        NSLog(@"倒计时结束");
    }];
    
    [self.myScroll addSubview:self.countDownButton];
    //------- 按钮的属性设置 -------//
    self.countDownButton.frame = CGRectMake(accountTextField.right+10, accountTextField.top,SCREEN_WIDTH -accountTextField.width -10 - 43*2, 40);
    [self.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.countDownButton setTitleColor:SKColorWithHex(0x4444444) forState:UIControlStateNormal];
    [self.countDownButton setTitleColor:SKColorWithHex(0x999999) forState:UIControlStateDisabled];
    self.countDownButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
    [self.myScroll addSubview:self.countDownButton];
}


#pragma  mark---注册处理
-(void)registerDeal:(UIButton*)sender
{
    UITextField * phoneTextField = [self.myScroll viewWithTag:20000000];
    if (IsStrEmpty(phoneTextField.text)) {
        [self.view makeToast:@"手机号不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }
    UITextField * yanZhengTextField = [self.myScroll viewWithTag:20000001];
    if (IsStrEmpty(yanZhengTextField.text)) {
        [self.view makeToast:@"验证码不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }

    UITextField * passwordTextField = [self.myScroll viewWithTag:20000002];
    if (IsStrEmpty(passwordTextField.text)) {
        [self.view makeToast:@"密码不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }
    UITextField *regNumTextField = [self.myScroll viewWithTag:20000003];
    NSString *mobile = phoneTextField.text;
    NSString *code = yanZhengTextField.text;
    NSString *password = passwordTextField.text;
    NSString *regNum = regNumTextField.text;
    if (self.xiYiBtn.isSelected) {
        if (self.myImage) {
                // 已签名 提交注册
                if (self.wxInfo) {
                    // 绑定
                    [self bindMobileWithCode:code Mobile:mobile Password:password RegNum:regNum SignImg:self.myImage Uid:self.wxInfo.uid LoginKey:self.wxInfo.loginKey];
                }else {
                    // 注册
                    [self registWithCode:code Mobile:mobile Password:password RegNum:regNum SignImg:self.myImage];
                }
            }else {
                // 未签名 去签名
                SignViewController *vc = [[SignViewController alloc] init];
                SKWeakSelf;
                vc.signResult = ^(UIImage *signImage) {
                    if (signImage) {
                        weakSelf.myImage = signImage;
                    }
                };
                [self.navigationController pushViewController:vc animated:true];
            }
    }else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"请阅读并确认已阅读用户协议" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [self presentViewController:alert animated:true completion:nil];
    }
}


-(void)initNav
{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton  * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
    [backBtn setTitle:@"  返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:SKColorWithHex(0x333333) forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backDeal:) forControlEvents:UIControlEventTouchUpInside];
    self.gk_navLeftBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:backBtn] ;
    self.gk_navItemLeftSpace = 10;
}
-(void)backDeal:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIScrollView*)myScroll
{
    if (_myScroll == nil) {
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.frame = CGRectMake(0, SKTopBar_Height, SCREEN_WIDTH, SCREENH_HEIGHT- SKTopBar_Height); // frame中的size指UIScrollView的可视范围
        scrollView.backgroundColor = [UIColor whiteColor];
        scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREENH_HEIGHT);
        [self.view addSubview:scrollView];
        _myScroll = scrollView;
        
        [self.view sendSubviewToBack:_myScroll];
    }
    return _myScroll;

}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self hideNavLine];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGRect textFieldRect  = [self.view convertRect:self.currentTextField.frame fromView:self.myScroll];
    SKLog(@"%f",textFieldRect.origin.y+ textFieldRect.size.height - keyboardRect.origin.y);
    if (self.currentTextField.bottom+ SKTopBar_Height - keyboardRect.origin.y > 0) {
        self.myScroll.top =-(self.currentTextField.bottom+SKTopBar_Height - keyboardRect.origin.y);
        [self.myScroll scrollRectToVisible:self.currentTextField.frame animated:YES];
    }
    
}
- (void)keyboardWillHide:(NSNotification *)notification {
    self.myScroll.top =SKTopBar_Height;
}

#pragma mark -- mark 网络请求

/**
 绑定手机号

 @param code 手机验证码
 @param mobile 手机号
 @param password 密码
 @param reg_num 邀请码
 @param signImage 签名图片
 @param uid uid
 @param loginKey loginkey
 */
- (void)bindMobileWithCode:(NSString *)code Mobile:(NSString *)mobile Password:(NSString *)password RegNum:(NSString *)reg_num SignImg:(UIImage *)signImage Uid:(NSString *)uid LoginKey:(NSString *)loginKey {
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:@{@"code":code,
                                                                                 @"mobile":mobile,
                                                                                 @"password":password,
                                                                                 @"uid":uid,
                                                                                 @"loginKey":loginKey}];
    if (reg_num.length > 0) {
        [param addEntriesFromDictionary:@{@"reg_num":reg_num}];
    }
    NSData *data = UIImageJPEGRepresentation(signImage, 0.1);
    SKWeakSelf;
    [YQNetworking uploadFileWithUrl:@"Login/bindMobile" parameters:param fileData:data type:@"file.jpg" name:@"img" mimeType:@"imge/jpeg" reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        YPLoginBaseClass * baseLogin = [YPLoginBaseClass modelObjectWithDictionary:response];
        if ([baseLogin.status isEqualToString:@"ok"]) {
            NSDictionary * dic = (NSDictionary *)response;
            SKUserUserDefaults_Save(dic[@"user_info"], @"UserInfo");
            [UserInfoSingleton shareInstance].userInfo = baseLogin.userInfo;
            if (weakSelf.myRegisterResult) {
                weakSelf.myRegisterResult([UserInfoSingleton shareInstance].userInfo);
            }
            [weakSelf registerSuccess];
        }
        else {
            [weakSelf showMessage:SafeString(baseLogin.msg)];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}

/**
 注册

 @param code code
 @param mobile mobile
 @param password 密码
 @param reg_num 邀请码
 @param signImage 签名图片
 */
- (void)registWithCode:(NSString *)code Mobile:(NSString *)mobile Password:(NSString *)password RegNum:(NSString *)reg_num SignImg:(UIImage *)signImage {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (code) {
        [param addEntriesFromDictionary:@{@"code":code}];
    }
    if (mobile) {
        [param addEntriesFromDictionary:@{@"mobile":mobile}];
    }
    if (password) {
        [param addEntriesFromDictionary:@{@"password":password}];
    }
    if (reg_num.length > 0) {
        [param addEntriesFromDictionary:@{@"reg_num":reg_num}];
    }
    NSData *data = UIImageJPEGRepresentation(signImage, 0.1);
    SKWeakSelf;
    [YQNetworking uploadFileWithUrl:@"Login/regV2" parameters:param fileData:data type:@"file.jpg" name:@"img" mimeType:@"imge/jpeg" reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        YPLoginBaseClass * baseLogin = [YPLoginBaseClass modelObjectWithDictionary:response];
        if ([baseLogin.status isEqualToString:@"ok"]) {
            NSDictionary * dic = (NSDictionary *)response;
            SKUserUserDefaults_Save(dic[@"user_info"], @"UserInfo");
            [UserInfoSingleton shareInstance].userInfo = baseLogin.userInfo;
            if (weakSelf.myRegisterResult) {
                weakSelf.myRegisterResult([UserInfoSingleton shareInstance].userInfo);
            }
            [weakSelf registerSuccess];
        }
        else {
            [weakSelf showMessage:SafeString(baseLogin.msg)];
        }
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
    }];
}


#pragma mark -- mark 业务逻辑

/**
 注册&绑定成功之后
 */
- (void)registerSuccess {
    CertifyViewController *vc = [[CertifyViewController alloc] init];
    SKWeakSelf;
    vc.certifyResultBlock = ^(BOOL success) {
        if (success) {
            [weakSelf.navigationController popToRootViewControllerAnimated:true];
        }
    };
    [self.navigationController pushViewController:vc animated:true];
}

@end
